import router from "@/router";
import store from "@/store";
import { Notify } from "vant";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, toLogin } from "chaos-sso-util";
NProgress.configure({
  showSpinner: false,
});
// 白名单
const whiteList = [
  "/login",
  "/auth-redirect",
  "/bind",
  "/register",
  "/EmpInfoRegForm",
];
const CALL_PAGE_NAME = "codeCallback";
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.name === CALL_PAGE_NAME) {
    next(); // 跳转
    NProgress.done();
  } else if (getToken()) {
    if (store.getters.roles.length === 0) {
      store
        .dispatch("GetInfo")
        .then(() => {
          next({ ...to, replace: true });
        })
        .catch((err) => {
          store.dispatch("FedLogOut").then(() => {
            Notify({ type: "danger", message: err });
            next({ path: "/" });
          });
        });
    } else {
      next();
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      toLogin();
      NProgress.done();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
